package top.byfree.jbyan.saber.bean.dto

import cn.dev33.satoken.stp.StpUtil
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.Size
import top.byfree.jbyan.saber.bean.IS_DELETE_NO
import top.byfree.jbyan.saber.bean.pojo.Menu
import top.byfree.jbyan.saber.bean.vo.UserVo
import top.byfree.jbyan.saber.common.AddGroup
import top.byfree.jbyan.saber.common.UpdateGroup
import java.time.LocalDateTime

/**
 * 用户 Dto
 *
 * @author jbyan
 * @since 21/3/2024
 */
data class MenuDto(
    /** 菜单编号 */
    @field:NotBlank(groups = [UpdateGroup::class], message = "修改菜单时菜单编号不能为空")
    var menuId: String?,
    /** 菜单名称 */
    @field:Size(min = 2, max = 12, message = "菜单名称需要在2-12位之间")
    @field:NotBlank(groups = [AddGroup::class], message = "菜单名称不能为空")
    var menuName: String?,
    /** 父菜单 */
    @field:NotBlank(groups = [AddGroup::class], message = "父菜单编号不能为空")
    var parentId: String?,
    /** 菜单权限 */
    @field:NotBlank(groups = [AddGroup::class], message = "菜单权限不能为空")
    var perms: String?,
    /** 路由地址 */
    var path: String?,
    /** 是否外链 */
    var isFrame: Int = 0,
    /** 菜单类型 */
    var menuType: String?,
    /** 菜单状态 */
    var status: Int = 0,
    /** 按钮类型 */
    var btnType: String?,
    /** 是否隐藏 */
    var visible: Int = 0,
    /** 图标 */
    var icon: String?,
    /** 备注 */
    var remark: String?,
    /** 排序编号 */
    var orderNum: Int = 0,
    /** 组件 */
    var component: String?
) {

    fun toMenu(cMenuId: String? = null, type: Class<*> = UpdateGroup::class.java): Menu {
        val userVo = StpUtil.getSession().get("user") as UserVo
        val menu = Menu {
            menuId = cMenuId?.let { cMenuId } ?: this@MenuDto.menuId!!
            gmtModify = LocalDateTime.now()
            modifyBy = userVo.username
            status = this@MenuDto.status
            orderNum = this@MenuDto.orderNum
            isFrame = this@MenuDto.isFrame
            visible = this@MenuDto.visible
        }
        menuName?.let { menu.menuName = it }
        menuType?.let { menu.menuType = it }
        path?.let { menu.path = it }
        icon?.let { menu.icon = it }
        btnType?.let { menu.btnType = it }
        component?.let { menu.component = it }
        remark?.let { menu.remark = it }
        parentId?.let { menu.parentId = it }
        perms?.let { menu.perms = it }

        if (type == AddGroup::class.java) {
            menu.createBy = userVo.username
            menu.gmtCreate = LocalDateTime.now()
            menu.isDelete = IS_DELETE_NO
        }

        return menu
    }
}